﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ManageData
{
    internal class 添加实体
    {
        void MyMethod()
        {
            // 添加单个实体
            using (var db = new BasicDbContext())
            {
                var entity = new BasicEntity { Text = "text" };
                db.Add(entity);
                db.BasicEntities.Add(entity);
                db.SaveChanges();
            }

            // 添加多个实体
            using (var db = new BasicDbContext())
            {
                var entity1 = new BasicEntity { Text = "text" };
                var entity2 = new BasicEntity { Text = "text" };
                var entityM = new MainEntity { Number = 6 };
                var entities = new object[] { entity1, entity2, entityM };

                db.AddRange(entity1, entity2, entityM);

                db.AddRange(entities);

                db.BasicEntities.AddRange(entity2, entity1);
                db.MainEntities.AddRange(entityM);

                db.SaveChanges();
            }


            // 同时添加多个相关实体
            using (var db = new BasicDbContext())
            {
                var mainEntity = new MainEntity
                {
                    Number = 6,
                    SubEntities = new List<SubEntity>
        {
            new SubEntity { Time = DateTimeOffset.Now },
            new SubEntity { Time = DateTimeOffset.Now.AddDays(1) }
        }
                };

                db.MainEntities.Add(mainEntity);
                db.SaveChanges();
            }

            // 在添加过程中逐步完善引用关系
            using (var db = new BasicDbContext())
            {
                var mainEntity = new MainEntity { Number = 6 };

                var sub1 = new SubEntity { Time = DateTimeOffset.Now };
                var sub2 = new SubEntity { Time = DateTimeOffset.Now.AddDays(1) };

                //①
                mainEntity.SubEntities.Add(sub1);
                mainEntity.SubEntities.Add(sub2);

                //②
                sub1.MainEntity = mainEntity;
                sub2.MainEntity = mainEntity;

                //③
                db.MainEntities.Add(mainEntity);

                //④
                db.SubEntities.AddRange(sub1, sub2);

                db.SaveChanges();
            }
        }
    }

}